package com.tsingtree.sys.modular.system.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.tsingtree.base.auth.context.LoginContextHolder;
import com.tsingtree.base.auth.model.LoginUser;
import com.tsingtree.base.consts.ConstantsContext;
import com.tsingtree.roses.core.util.ToolUtil;
import com.tsingtree.roses.kernel.model.exception.ServiceException;
import com.tsingtree.roses.kernel.model.exception.enums.CoreExceptionEnum;
import com.tsingtree.sys.core.auth.cache.SessionManager;
import com.tsingtree.sys.core.constant.Const;
import com.tsingtree.sys.core.exception.enums.BizExceptionEnum;
import com.tsingtree.sys.modular.system.entity.SysUser;
import com.tsingtree.sys.modular.system.model.UploadResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.InputStream;

/**
 * <p>
 * 文件信息表
 * 服务实现类
 * </p>
 *
 * @author  jagger
 * @since 2018-12-07
 */
@Service
@Slf4j
public class FileInfoService {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SessionManager sessionManager;

    private OSS client;

    @PostConstruct
    public void init() {
        if(StringUtils.hasText(Const.OSS_BUCKET)){
            client = new OSSClient(Const.OSS_ENDPOINT, Const.OSS_AK, Const.OSS_SK);
        }
    }

    private boolean uploadFileResult(InputStream in, String fileName, String contextType) throws Exception {
        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(in.available());
        objectMeta.setContentType(contextType);
        PutObjectResult result = client.putObject(Const.OSS_BUCKET, fileName, in, objectMeta);
        return !StringUtils.isEmpty(result.getETag());
    }

    /**
     * 更新头像
     *
     * @author jagger
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateAvatar(String fileId) {
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        if (currentUser == null) {
            throw new ServiceException(CoreExceptionEnum.NO_CURRENT_USER);
        }

        SysUser user = userService.getById(currentUser.getId());
        currentUser.setAvatar(fileId);
        String token = LoginContextHolder.getContext().getToken();
        sessionManager.createSession(token, currentUser);
        //更新用户的头像
        user.setAvatar(fileId);
        userService.updateById(user);
    }

    /**
     * 上传文件（指定上传路径）
     *
     */
    public UploadResult uploadFile(MultipartFile file, long userId) {
        String fileSavePath = ConstantsContext.getFileUploadPath();
        return this.uploadFile(file, fileSavePath, userId);
    }

    /**
     * 上传文件（指定上传路径）
     *
     * @author fengshuonan
     * @Date 2019-05-04 17:18
     */
    public UploadResult uploadFile(MultipartFile file, String fileSavePath, long userId) {
        UploadResult uploadResult = new UploadResult();

        //生成文件的唯一id
        String fileId = IdWorker.getIdStr();
        uploadResult.setFileId(fileId);

        //获取文件后缀
        String fileSuffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
        uploadResult.setFileSuffix(fileSuffix);

        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        uploadResult.setOriginalFilename(originalFilename);
        String path = "/upload/admin/" + userId + "/";
        //生成文件的最终名称
        String finalName = fileId + "." + ToolUtil.getFileSuffix(originalFilename);
        uploadResult.setFinalName(path + finalName);
        try {
            //保存文件到指定目录
            File f = new File(fileSavePath + path);
            if(!f.exists())
                if(!f.mkdirs()){
                    throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
                }
            File newFile = new File(fileSavePath + path +  finalName);
            file.transferTo(newFile);
        } catch (Exception e) {
            log.error("上传文件错误！", e);
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return uploadResult;

    }


    public UploadResult uploadFileOss(MultipartFile file, long userId) {
        UploadResult uploadResult = new UploadResult();

        //生成文件的唯一id
        String fileId = IdWorker.getIdStr();
        uploadResult.setFileId(fileId);

        //获取文件后缀
        String fileSuffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
        uploadResult.setFileSuffix(fileSuffix);

        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        uploadResult.setOriginalFilename(originalFilename);
        String path = "upload/admin/" + userId + "/";
        //生成文件的最终名称
        String ext = ToolUtil.getFileSuffix(originalFilename).toLowerCase();
        String contextType = file.getContentType();
        if (ext.equalsIgnoreCase("jpeg") ||
                ext.equalsIgnoreCase("jpg") ||
                ext.equalsIgnoreCase("png")) {
            contextType = "image/jpg";
        }
        String finalName = fileId + "." + ToolUtil.getFileSuffix(originalFilename);
        uploadResult.setFinalName("/" + path + finalName);
        try {
            boolean flag = this.uploadFileResult(file.getInputStream(), path + finalName, contextType);
            if(!flag){
                log.error("save ali oss failed");
            }
        } catch (Exception e) {
            log.error("上传文件错误！", e);
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }

        return uploadResult;
    }

    public UploadResult uploadApk(MultipartFile file) {
        UploadResult uploadResult = new UploadResult();

        //生成文件的唯一id
        String fileId = IdWorker.getIdStr();
        uploadResult.setFileId(fileId);

        //获取文件后缀
        String fileSuffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
        uploadResult.setFileSuffix(fileSuffix);

        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        uploadResult.setOriginalFilename(originalFilename);
        String path = "/www/upload/android/";
        //生成文件的最终名称
        String finalName = "luvvjoy.apk";
        uploadResult.setFinalName(path + finalName);
        try {
            //保存文件到指定目录
            File f = new File(path);
            if(!f.exists())
                if(!f.mkdirs()){
                    throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
                }
            File newFile = new File( path +  finalName);
            file.transferTo(newFile);
        } catch (Exception e) {
            log.error("上传文件错误！", e);
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return uploadResult;

    }
}
